<?php

/**
 * Class advertising
 * 广告插件
 */
class editor extends AWS_CONTROLLER
{
    private $editType = '';
    public function __construct()
    {
        parent::__construct();

        $this->info = $this->model('plugin')->get_info('editor');
        $this->config=$this->get_config();
    }
    public function get_config(){
        $config=json_decode($this->info['config'],true);
        foreach ($config as $key => $value) {
            $config[$key] = $value['value'];
        }
        return $config;
    }

    /**
     * 插件安装方法
     * @return bool
     */
    public function install($addon_name)
    {
      $config=json_decode($this->info['config'],true);
      $config['type']['value']='ckeditor';
      $this->model('editor')->update('plugins',['config'=>json_encode($config,JSON_UNESCAPED_UNICODE)],'name="'.$addon_name.'"');
        return $this->model('plugin')->install($addon_name);        //此处方法可以自行实现
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall($addon_name)
    {
        return $this->model('plugin')->uninstall($addon_name);         //此处方法可以自行实现
    }

    /**
     * 插件启用方法
     */
    public function enable($addon_name)
    {
        return $this->model('plugin')->enable($addon_name);             //此处方法可以自行实现
    }

    /**
     * 插件禁用方法
     */
    public function disable($addon_name)
    {
      $config=json_decode($this->info['config'],true);
      $config['type']['value']='ckeditor';
      $this->model('editor')->update('plugins',['config'=>json_encode($config,JSON_UNESCAPED_UNICODE)],'name="'.$addon_name.'"');
        return $this->model('plugin')->disable($addon_name);           
    }

    public function init($parm){
    	// var_dump($this->info['state']);
        if($this->info['state']==1)
          $type=$this->config['type'];
        else
          $type='ckeditor';
       PLUTPL::assign('path',str_replace('?','',base_url()).'/plugins/wc_editor/static');
       PLUTPL::assign('type',$type);
       PLUTPL::assign('user_info',$this->user_info);
       PLUTPL::assign('config',$this->config);
       PLUTPL::assign('parm',$parm);
       PLUTPL::output("editor/init");
    }

    public function upload_file(){
            if(!$this->user_info['permission']['upload_attach'] and !($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator'])  and $parm['cat']!='avatar'){
                echo json_encode(['error'=>1,'message'=>'没有上传权限']); exit();
            }
            if(get_hook_info('osd')['state']==1 and get_hook_config('osd')['group']['base']['config']['status']['value']!='no'){
                $ret=hook('osd','upload_files',['type'=>$this->config['type'],'field'=>'upload','cat'=>$_GET['cat']]);
                echo json_encode($ret);exit();
            }else{
                $files=$_FILES['upload'];
                $ext = strtolower(pathinfo(@$files['name'],PATHINFO_EXTENSION));
                $config=get_setting('allowed_upload_types');
                $config=explode(',',$config);
                if(!in_array($ext,$config)){
                        if($this->config['type']=='ckeditor'){
                          echo json_encode(['uploaded'=>0,'error'=>['message'=>'文件类型不符合'],]); exit();
                        }else{
                          echo json_encode(['error'=>1,'msg'=>'文件类型不符合']); exit();
                        }
                }
                if($this->config['fileMaxSize']*1024*1024<$files['size']){
                        if($this->config['type']=='ckeditor'){
                          echo json_encode(['uploaded'=>0,'error'=>['message'=>'文件大小超出限制'],]); exit();
                        }else{
                          echo json_encode(['error'=>1,'msg'=>'文件大小超出限制']); exit();
                        }
                }
                $_savepath='/uploads/'.$_GET['cat'].'/'.date('Ymd');
                $savepath=base_url().$_savepath;
                $savepath=str_replace(http_type().$_SERVER['HTTP_HOST'], '', $savepath);
                $path='.'.$_savepath;
                    // 判断文件类型
                    // 判断是否存在上传到的目录
                    if (!is_dir($path)){
                        mkdir($path,0777,true);
                    }
                    // 生成唯一的文件名
                    $fileName = md5(uniqid(microtime(true),true)).'.'.$ext;
                    // 将文件名拼接到指定的目录下
                    $destName = $path."/".$fileName;
                    // 进行文件移动
                    if (!move_uploaded_file($files['tmp_name'],$destName)){
                          echo json_encode([
                                'uploaded'=>0,
                                'error'=>[
                                    'message'=>'文件上传失败'
                                ],
                          ]); 
                           exit();
                    }
              if($this->config['type']=='ckeditor'){
                  echo json_encode(['uploaded'=>1,'fileName'=>$files['name'],'url'=>$savepath."/".$fileName,]);exit();
              }elseif ($this->config['type']=='wangeditor') {
                  echo json_encode(['errno'=>0,'data'=>["$files[name]"=>$savepath."/".$fileName]]);exit();
                  # code...
              }      
            }



        }

  public function upload(){
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(__DIR__."/static/ueditor/config.json")), true);

        $action = $_GET['action'];
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
            /* 上传涂鸦 */
            case 'uploadscrawl':
            /* 上传视频 */
            case 'uploadvideo':
            /* 上传文件 */
            case 'uploadfile':
                $result = $this->action_upload($CONFIG);
                break;
            /* 列出图片 */
            case 'listimage':
                $result = $this->action_list($CONFIG);
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->action_list($CONFIG);
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->action_crawler($CONFIG);
                break;
            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
  }
    private function action_upload($CONFIG){
            if(!$this->user_info['permission']['upload_attach'] and !($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator'])  and $parm['cat']!='avatar'){
                echo json_encode(['error'=>1,'state'=>'没有上传权限']); exit();
            }
            /* 上传配置 */
            $base64 = "upload";
            switch (htmlspecialchars($_GET['action'])) {
                case 'uploadimage':
                    $config = array(
                        "pathFormat" => $CONFIG['imagePathFormat'],
                        "maxSize" => $this->config['fileMaxSize']*1024*1024,
                        "allowFiles" => $CONFIG['imageAllowFiles']
                    );
                    $fieldName = $CONFIG['imageFieldName'];
                    break;
                case 'uploadscrawl':
                    $config = array(
                        "pathFormat" => $CONFIG['scrawlPathFormat'],
                        "maxSize" => $CONFIG['scrawlMaxSize'],
                        "allowFiles" => $CONFIG['scrawlAllowFiles'],
                        "oriName" => "scrawl.png"
                    );
                    $fieldName = $CONFIG['scrawlFieldName'];
                    $base64 = "base64";
                    break;
                case 'uploadvideo':
                    $config = array(
                        "pathFormat" => $CONFIG['videoPathFormat'],
                        "maxSize" => $this->config['fileMaxSize']*1024*1024,
                        "allowFiles" => $CONFIG['videoAllowFiles']
                    );
                    $fieldName = $CONFIG['videoFieldName'];
                    break;
                case 'uploadfile':
                default:
                    $config = array(
                        "pathFormat" => $CONFIG['filePathFormat'],
                        "maxSize" => $this->config['fileMaxSize']*1024*1024,
                        "allowFiles" => $CONFIG['fileAllowFiles']
                    );
                    $fieldName = $CONFIG['fileFieldName'];
                    break;
            }
            $config['pathFormat']=base_url().'/uploads/files_user'.$this->user_id.'/'.$_GET['cat'].'/{time}{rand:6}';
            $config['pathFormat']=str_replace(http_type().$_SERVER['HTTP_HOST'], '', $config['pathFormat']);
            /* 生成上传实例对象并完成上传 */
            if(get_hook_info('osd')['state']==1){
                $_config=get_hook_config('osd');
                foreach ($_config['group'] as $key => $value) {
                    foreach ($value['config'] as $k => $v) {
                        $configs[$key][$k] = $v['value'];
                    }
                }
                if($configs['base']['status']=='no'){
                    require __DIR__.'/static/ueditor/php/Uploader.php';
                    $up = new Uploader($fieldName, $config, $base64);
                    $data = $up->getFileInfo();
                }else{
                    $data=hook('osd','upload_files',['type'=>'ueditor','cat'=>$_GET['cat']]);
                }


              }else{
                require __DIR__.'/static/ueditor/php/Uploader.php';
                $up = new Uploader($fieldName, $config, $base64);
                $data = $up->getFileInfo();
                
              }
            /**
             * 得到上传文件所对应的各个参数,数组结构
             * array(
             *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
             *     "url" => "",            //返回的地址
             *     "title" => "",          //新文件名
             *     "original" => "",       //原始文件名
             *     "type" => ""            //文件类型
             *     "size" => "",           //文件大小
             * )
             */
            /* 返回数据 */
            return json_encode($data);
    }

    private function action_list($CONFIG){
        /* 判断类型 */
        switch ($_GET['action']) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG['fileManagerAllowFiles'];
                $listSize = $CONFIG['fileManagerListSize'];
                $path = $CONFIG['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $CONFIG['imageManagerAllowFiles'];
                $listSize = $CONFIG['imageManagerListSize'];
                $path = $CONFIG['imageManagerListPath'];
        }
            $path='/uploads/files_user'.$this->user_id.'/'.$_GET['cat'].'/';

        if(get_hook_info('osd')['state']==1){
            $_config=get_hook_config('osd');
            foreach ($_config['group'] as $key => $value) {
                foreach ($value['config'] as $k => $v) {
                    $config[$key][$k] = $v['value'];
                }
            }
            if($config['base']['status']=='no'){
                    $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
                    /* 获取参数 */
                    $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
                    $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
                    $end = $start + $size;
                    /* 获取文件列表 */
                    $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
                    $files = $this->getfiles($path, $allowFiles);
                    if (!count($files)) {
                        return json_encode(array(
                            "state" => "no match file",
                            "list" => array(),
                            "start" => $start,
                            "total" => count($files)
                        ));
                    }
                    /* 获取指定范围的列表 */
                    $len = count($files);
                    for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
                        $list[] = $files[$i];
                    }

            }else{

                if($config['base']['status']=='oss')
                    $CONFIG['imageManagerUrlPrefix']=$CONFIG['fileManagerUrlPrefix']=http_type().$config['oss']['bucket'].'.'.$config['oss']['endpoint'];
                if($config['base']['status']=='cos')
                    $CONFIG['imageManagerUrlPrefix']=$CONFIG['fileManagerUrlPrefix']=http_type().$config['cos']['bucket'].'.cos.'.$config['cos']['region'].'.myqcloud.com';
                $list=hook('osd','listfiles',['page'=>$_GET['start'],'offset'=>$_GET['size'],'domin'=>$CONFIG['imageManagerUrlPrefix'],'type'=>$_GET['cat'],'allowFiles'=>$allowFiles]);
            }

        }else{

            $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
            /* 获取参数 */
            $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
            $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
            $end = $start + $size;
            /* 获取文件列表 */
            $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
            $files = $this->getfiles($path, $allowFiles);
            if (!count($files)) {
                return json_encode(array(
                    "state" => "no match file",
                    "list" => array(),
                    "start" => $start,
                    "total" => count($files)
                ));
            }
            /* 获取指定范围的列表 */
            $len = count($files);
            for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
                $list[] = $files[$i];
            }
            //倒序
            //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
            //    $list[] = $files[$i];
            //}
        }
        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));
        return $result;
    }

    private function action_crawler($CONFIG){
        set_time_limit(0);
        /* 上传配置 */
        $config = array(
            "pathFormat" => $CONFIG['catcherPathFormat'],
            "maxSize" => $CONFIG['catcherMaxSize'],
            "allowFiles" => $CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $CONFIG['catcherFieldName'];
        /* 抓取远程图片 */
        $list = array();
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new \Famous\Libs\Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }
        /* 返回抓取数据 */
        return json_encode(array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        ));
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = array()) {
        if (!is_dir($path)) return null;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = array(
                            'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime'=> filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }

}